// 中间件系统统一导出文件
import { MiddlewareManager } from './MiddlewareManager.js';
import { AuthenticationMiddleware } from './AuthenticationMiddleware.js';
import { AuthorizationMiddleware } from './AuthorizationMiddleware.js';
import { ValidationMiddleware } from './ValidationMiddleware.js';
import { ErrorHandlingMiddleware } from './ErrorHandlingMiddleware.js';
import { LoggingMiddleware } from './LoggingMiddleware.js';
import { RateLimitingMiddleware } from './RateLimitingMiddleware.js';
import { config } from '../config.js';

/**
 * 中间件配置和初始化
 */
export class MiddlewareConfig {
    constructor() {
        this.manager = new MiddlewareManager();
        this.middlewares = {};
        this.initialized = false;
    }

    /**
     * 初始化所有中间件
     */
    async initialize() {
        if (this.initialized) {
            console.warn('[MiddlewareConfig] Already initialized');
            return;
        }

        try {
            console.log('🔧 Initializing middleware system...');

            // 1. 日志记录中间件（最高优先级）
            this.middlewares.logging = new LoggingMiddleware({
                priority: 10,
                logToFile: config.log?.file || false,
                logToConsole: config.log?.console !== false,
                logLevel: config.log?.level || 'info',
                includeRequestBody: config.env === 'development'
            });
            this.manager.register('logging', this.middlewares.logging);

            // 2. 限流中间件
            this.middlewares.rateLimit = new RateLimitingMiddleware({
                priority: 20,
                windowMs: 15 * 60 * 1000, // 15分钟
                maxRequests: config.env === 'development' ? 1000 : 100,
                skipPaths: ['/health', '/favicon.ico', '/config']
            });
            this.manager.register('rateLimit', this.middlewares.rateLimit);

            // 3. 认证中间件
            this.middlewares.auth = new AuthenticationMiddleware({
                priority: 50,
                jwtSecret: config.jwt.secret,
                jwtExpiresIn: config.jwt.expiresIn,
                skipPaths: [
                    '/health',
                    '/favicon.ico',
                    '/config',
                    '/api/users/login',
                    '/api/users/register',
                    '/api/auth/login',
                    '/api/auth/register'
                ]
            });
            this.manager.register('auth', this.middlewares.auth);

            // 4. 授权中间件
            this.middlewares.authorization = new AuthorizationMiddleware({
                priority: 60,
                skipPaths: [
                    '/health',
                    '/favicon.ico',
                    '/config',
                    '/api/users/login',
                    '/api/users/register',
                    '/api/auth/login',
                    '/api/auth/register'
                ]
            });
            this.manager.register('authorization', this.middlewares.authorization);

            // 5. 请求验证中间件
            this.middlewares.validation = new ValidationMiddleware({
                priority: 70,
                strictMode: config.env === 'production'
            });
            this.manager.register('validation', this.middlewares.validation);

            // 6. 错误处理中间件（最低优先级）
            this.middlewares.errorHandler = new ErrorHandlingMiddleware({
                priority: -100,
                logToFile: config.log?.file || false,
                includeStackTrace: config.env === 'development',
                notifyOnCritical: config.env === 'production'
            });
            this.manager.register('errorHandler', this.middlewares.errorHandler);

            this.initialized = true;
            console.log('✅ Middleware system initialized successfully');
            
            // 打印中间件信息
            this.printMiddlewareInfo();
        } catch (error) {
            console.error('❌ Failed to initialize middleware system:', error);
            throw error;
        }
    }

    /**
     * 获取全局中间件数组（按优先级排序）
     * @returns {Array} 中间件函数数组
     */
    getGlobalMiddlewares() {
        if (!this.initialized) {
            throw new Error('Middleware system not initialized. Call initialize() first.');
        }

        const globalMiddlewares = [];
        
        // 按优先级顺序添加中间件
        const sortedMiddlewares = this.manager.getMiddlewaresByPriority();
        
        for (const middleware of sortedMiddlewares) {
            if (middleware.name === 'errorHandler') {
                // 错误处理中间件需要特殊处理（4个参数）
                continue;
            }
            globalMiddlewares.push(middleware.instance.getMiddleware());
        }
        
        return globalMiddlewares;
    }

    /**
     * 获取错误处理中间件
     * @returns {Function} 错误处理中间件函数
     */
    getErrorHandler() {
        if (!this.initialized) {
            throw new Error('Middleware system not initialized. Call initialize() first.');
        }
        return this.middlewares.errorHandler.getMiddleware();
    }

    /**
     * 获取404处理中间件
     * @returns {Function} 404处理中间件函数
     */
    getNotFoundHandler() {
        if (!this.initialized) {
            throw new Error('Middleware system not initialized. Call initialize() first.');
        }
        return this.middlewares.errorHandler.createNotFoundMiddleware();
    }

    /**
     * 获取特定中间件实例
     * @param {string} name - 中间件名称
     * @returns {Object} 中间件实例
     */
    getMiddleware(name) {
        if (!this.initialized) {
            throw new Error('Middleware system not initialized. Call initialize() first.');
        }
        return this.middlewares[name];
    }

    /**
     * 创建路由级别的中间件组合
     * @param {Array} middlewareNames - 要包含的中间件名称数组
     * @returns {Array} 中间件函数数组
     */
    createRouteMiddlewares(middlewareNames = []) {
        if (!this.initialized) {
            throw new Error('Middleware system not initialized. Call initialize() first.');
        }

        const routeMiddlewares = [];
        
        for (const name of middlewareNames) {
            const middleware = this.middlewares[name];
            if (middleware) {
                routeMiddlewares.push(middleware.getMiddleware());
            } else {
                console.warn(`[MiddlewareConfig] Unknown middleware: ${name}`);
            }
        }
        
        return routeMiddlewares;
    }

    /**
     * 创建认证保护的路由中间件
     * @param {Array} requiredRoles - 必需的角色数组
     * @param {Array} requiredPermissions - 必需的权限数组
     * @returns {Array} 中间件函数数组
     */
    createProtectedRouteMiddlewares(requiredRoles = [], requiredPermissions = []) {
        if (!this.initialized) {
            throw new Error('Middleware system not initialized. Call initialize() first.');
        }

        const middlewares = [];
        
        // 认证中间件（必需）
        middlewares.push(this.middlewares.auth.getMiddleware());
        
        // 角色检查
        if (requiredRoles.length > 0) {
            middlewares.push(this.middlewares.authorization.requireRoles(requiredRoles));
        }
        
        // 权限检查
        if (requiredPermissions.length > 0) {
            middlewares.push(this.middlewares.authorization.requirePermissions(requiredPermissions));
        }
        
        return middlewares;
    }

    /**
     * 创建验证中间件
     * @param {Object} schema - 验证模式
     * @returns {Function} 验证中间件函数
     */
    createValidationMiddleware(schema) {
        if (!this.initialized) {
            throw new Error('Middleware system not initialized. Call initialize() first.');
        }
        return this.middlewares.validation.validate(schema);
    }

    /**
     * 创建限流中间件
     * @param {Object} options - 限流选项
     * @returns {Function} 限流中间件函数
     */
    createRateLimitMiddleware(options = {}) {
        return RateLimitingMiddleware.createRateLimit(options);
    }

    /**
     * 打印中间件信息
     */
    printMiddlewareInfo() {
        console.log('\n📋 Registered Middlewares:');
        const middlewares = this.manager.getMiddlewaresByPriority();
        
        for (const middleware of middlewares) {
            const status = middleware.enabled ? '✅' : '❌';
            console.log(`  ${status} ${middleware.name} (Priority: ${middleware.priority})`);
        }
        
        console.log(`\n📊 Total: ${middlewares.length} middlewares registered\n`);
    }

    /**
     * 获取中间件统计信息
     * @returns {Object} 统计信息
     */
    getStats() {
        if (!this.initialized) {
            return { initialized: false };
        }

        return {
            initialized: true,
            totalMiddlewares: Object.keys(this.middlewares).length,
            enabledMiddlewares: this.manager.getEnabledMiddlewares().length,
            requestStats: this.middlewares.logging?.getRequestStats() || {},
            rateLimitStats: this.middlewares.rateLimit?.getRateLimitStats() || {},
            errorStats: this.middlewares.errorHandler?.getErrorStats() || {}
        };
    }

    /**
     * 重置所有统计信息
     */
    resetStats() {
        if (!this.initialized) {
            console.warn('[MiddlewareConfig] Not initialized');
            return;
        }

        this.middlewares.logging?.resetRequestStats();
        this.middlewares.rateLimit?.resetRateLimit();
        this.middlewares.errorHandler?.resetErrorStats();
        
        console.log('✅ All middleware statistics reset');
    }

    /**
     * 启用/禁用中间件
     * @param {string} name - 中间件名称
     * @param {boolean} enabled - 是否启用
     */
    setMiddlewareEnabled(name, enabled) {
        if (!this.initialized) {
            throw new Error('Middleware system not initialized. Call initialize() first.');
        }

        const middleware = this.middlewares[name];
        if (middleware) {
            if (enabled) {
                middleware.enable();
                this.manager.enable(name);
            } else {
                middleware.disable();
                this.manager.disable(name);
            }
            console.log(`✅ Middleware '${name}' ${enabled ? 'enabled' : 'disabled'}`);
        } else {
            console.warn(`[MiddlewareConfig] Unknown middleware: ${name}`);
        }
    }
}

// 创建全局实例
export const middlewareConfig = new MiddlewareConfig();

// 便捷导出
export {
    MiddlewareManager,
    AuthenticationMiddleware,
    AuthorizationMiddleware,
    ValidationMiddleware,
    ErrorHandlingMiddleware,
    LoggingMiddleware,
    RateLimitingMiddleware
};

// 便捷方法导出
export const initializeMiddlewares = () => middlewareConfig.initialize();
export const getGlobalMiddlewares = () => middlewareConfig.getGlobalMiddlewares();
export const getErrorHandler = () => middlewareConfig.getErrorHandler();
export const getNotFoundHandler = () => middlewareConfig.getNotFoundHandler();
export const createProtectedRoute = (roles, permissions) => 
    middlewareConfig.createProtectedRouteMiddlewares(roles, permissions);
export const createValidation = (schema) => 
    middlewareConfig.createValidationMiddleware(schema);
export const createRateLimit = (options) => 
    middlewareConfig.createRateLimitMiddleware(options);

export default middlewareConfig;